package org.rain.core.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.rain.common.model.R;
import org.rain.core.BaseController;
import org.rain.core.querygen.QueryWrapperGenerate;
import org.rain.core.storage.model.entity.SysFile;
import org.rain.core.storage.model.req.SysFileReq;
import org.rain.core.storage.model.resp.SysFileResp;
import org.rain.core.storage.service.ISysFileService;
import org.rain.core.util.Pages;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * created by yangtong on 2025/4/8 16:45:39
 * <br/>
 * 文件系统接口
 */
@RestController
@RequestMapping("/sys/file")
@Tag(name = "文件")
public class FileStorageController extends BaseController<SysFile, ISysFileService> {

    /**
     * 分页查询
     */
    @GetMapping("page")
    @Operation(summary = "分页查询", description = "分页查询")
    public R<IPage<SysFileResp>> page(@ParameterObject SysFileReq fileReq) {
        QueryWrapper<SysFile> qw = QueryWrapperGenerate.init(fileReq);
        IPage<SysFile> page = Pages.getPage();
        baseService.page(page, qw);
        return R.success(Pages.transPage(page, SysFile::toResp));
    }

    /**
     * 根据文件id删除文件
     */
    @DeleteMapping("delete")
    @Operation(summary = "根据文件id删除文件", description = "根据文件id删除文件")
    public R<String> delete(String fileId) {
        baseService.delete(fileId);
        return R.success("删除成功");
    }

    /**
     * 上传文件
     */
    @PostMapping("upload")
    @Operation(summary = "上传文件", description = "上传文件")
    public R<String> upload(@RequestPart MultipartFile file) {
        String fileId = baseService.upload(file);
        return R.success(fileId);
    }

    /**
     * 下载文件
     */
    @ApiResponse(
            responseCode = "200",
            description = "文件下载成功",
            content = @Content(
                    mediaType = "application/octet-stream",
                    schema = @Schema(type = "string", format = "binary")
            )
    )
    @Operation(summary = "下载文件", description = "下载文件")
    @GetMapping(value = "download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void download(String fileId) {
        baseService.download(fileId);
    }

}
